<template>
  <page-header-wrapper style="border: 1px solid rgb(235, 237, 240)" title="研究者费用申请" @back="() => $router.go(-1)">
    <a-card>
      <a-form-model layout="inline" ref="formRef">
        <!-- 基本信息 -->
        <a-row :gutter="[24, 12]">
          <a-col class="gutter-row" :span="8">
            <a-form-model-item label="经办人员:" labelAlign="left">
              <span>{{ $store.getters.userInfo.userName }}</span>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item label="申请日期:" labelAlign="left">
              <span>{{ date }}</span>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item label="收款总额:" labelAlign="left">
              <span>{{ totalAmt }}</span>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item label="选择项目:" labelAlign="left">
              <span>{{ $route.query.pname }}</span>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item label="选择中心:" labelAlign="left" :required="true">
              <a-select default-value="请选择" style="width: 183px" @change="handleCenterChange" v-model="centerName">
                <a-select-option
                  v-for="item in centerList"
                  :key="item.id"
                  :value="item.id"
                >{{ item.orgName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item label="选择科室:" labelAlign="left" :required="true">
              <a-select
                default-value="请选择"
                style="width: 183px"
                @change="handleDepartmentChange"
                v-model="orgDeptName"
              >
                <a-select-option
                  v-for="item in orgDeptList"
                  :key="item.id"
                  :value="item.id"
                >{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item label="收款人员:" labelAlign="left" :required="true">
              <a-select default-value="请选择" style="width: 183px" @change="handlePersonChange" v-model="personName">
                <a-select-option
                  v-for="item in personList"
                  :key="item.researchNo"
                  :value="item.researchNo"
                >{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item label="收款账号:" labelAlign="left" :required="true">
              <a-select default-value="请选择" style="width: 183px" @change="handleAccountChange" v-model="accountId">
                <a-select-option
                  v-for="item in accountList"
                  :key="item.id"
                  :value="item.id"
                >{{ item.bankCardNo }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item label="结算币种:" labelAlign="left">
              <span>{{ moneyType }}</span>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="24">
            <a-form-model-item label="申请事由:" labelAlign="left" :required="true">
              <a-textarea placeholder="请输入" style="width: 905px" :rows="3" v-model="applyReason" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- 费用事项 -->
        <FeeEdit @updateFee="updateFee" :mattersList="mattersList" :type="1"></FeeEdit>
        <div style="padding-top: 20px">
          <a-button type="primary" style="margin-left: 10px" :loading="submitting" @click="submit" > 提交 </a-button>
        </div>
      </a-form-model>
    </a-card>
  </page-header-wrapper>
</template>
<script>
import monitor from '@/utils/monitor'
import addResearch from '@/monitor/views/cost-apply/research/addResearch'
import moment from 'moment'
import {
  selectResearchCenter,
  selectResearchPerson,
  selectResearchAccount,
  getPmCommit
} from '@/api/cost/cost'
import ViewFile from './ViewFile'
import { getDepartmentList } from '@/api/common'
import FeeEdit from '../FeeEdit'
import { getApprovalDetail } from '@/api/overview/approval'

const watch = monitor(addResearch)

export default {
  name: 'AddResearcher',
  components: { ViewFile, FeeEdit },
  data () {
    return {
      proFlowId: null,
      formList: [],
      moneyType: 'RMB',
      applyReason: '',
      type: 1,
      totalAmt: 0,
      date: moment().format('YYYY年MM月DD日'), // 日期
      orgDeptList: [], // 科室
      orgDeptId: null,
      mattersList: [],
      loading: true,
      centerList: [],
      centerId: null,
      projectId: this.$route.query.id,
      personList: [],
      personId: null,
      accountList: [],
      accountId: null,
      centerName: '',
      orgDeptName: '',
      personName: '',
      accountName: '',
      centerMap: {},
      submitting: false,
      personMap: {}
    }
  },
  created () {
    this.projectId = this.$route.query.id
    this.getCenterList()
    this.getMattersList()
  },
  methods: watch({
    updateFee (val, totalAmt) {
      this.formList = val
      this.totalAmt = totalAmt
    },
    // 获取审批流详情
    async getMattersList () {
      if (!this.$route.query.id) {
        return
      }
      const res = await getApprovalDetail({
        proId: this.$route.query.id,
        type: this.type
      })
      res.feeCategoryList.forEach(i => {
        i.editable = false
        i.fileList = []
        i.amt = i.defaulted ? i.amt : ''
      })
      this.proFlowId = res.id
      this.mattersList = res.feeCategoryList
    },
    // 请求中心列表
    getCenterList () {
      selectResearchCenter({ proId: this.projectId })
        .then(res => {
          this.centerList = res
          res.forEach(item => {
            this.centerMap[item.id] = item
          })
        })
        .catch(() => {})
    },
    // 请求科室列表
    getDepartmentList () {
      getDepartmentList({ researchId: this.centerId })
        .then(res => {
          const orgDeptId = this.centerMap[this.centerId] ? this.centerMap[this.centerId].orgDeptId : ''
          this.orgDeptList = res.filter(item => orgDeptId.split(',').indexOf(item.id.toString()) >= 0)
          this.orgDeptList.unshift({ id: 19961996, name: '全部' })
        })
        .catch(() => {})
    },
    // 请求收款人员列表
    getPersonList () {
      const queryObj = {}
      queryObj.proId = this.projectId
      queryObj.orgDeptId = this.orgDeptId
      queryObj.researchId = this.centerName
      selectResearchPerson({ ...queryObj })
        .then(res => {
          this.personList = res
          res.forEach(item => {
            this.personMap[item.researchNo] = item
          })
        })
        .catch(() => {})
    },
    // 请求收款账户列表
    getAccountList () {
      const queryObj = {}
      queryObj.researchNo = this.personId
      queryObj.proId = this.projectId
      selectResearchAccount({ ...queryObj })
        .then(res => {
          this.accountList = res
          if (res && res.length > 0) this.accountId = res[0].id
        })
        .catch(() => {})
    },
    // 中心列表下拉改变
    handleCenterChange (value) {
      this.centerId = value
      this.orgDeptName = ''
      this.orgDeptId = null
      this.personId = null
      this.personName = ''
      this.accountId = null
      this.accountName = ''
      this.orgDeptList = []
      this.personList = []
      this.accountList = []
      this.getDepartmentList()
    },
    // 科室列表下拉改变
    handleDepartmentChange (value) {
      if (Number(value) === 19961996) {
        this.orgDeptId = null
      } else {
        this.orgDeptId = value
      }
      this.personId = null
      this.personName = ''
      this.accountId = null
      this.accountName = ''
      this.personList = []
      this.accountList = []
      this.getPersonList()
    },
    // 收款人员列表下拉改变
    handlePersonChange (value) {
      this.personId = value
      this.accountId = null
      this.accountName = ''
      this.accountList = []
      this.getAccountList()
    },
    // 账户列表下拉改变
    handleAccountChange (value) {
      this.accountId = value
    },
    // 提交
    submit () {
      if (!this.centerName || !this.orgDeptName || !this.personName || !this.accountId || !this.applyReason) {
        this.$message.error('请将必选项选完')
        return false
      }
      if (this.formList.length === 0) {
        this.$message.error('请至少添加一条费用事项')
        return
      }
      const target = this.formList.find(item => item.editable === true)
      if (target) {
        this.$message.error('请先将费用事项每行进行保存后再提交')
        return false
      }
      const applyTypeItem = this.formList.find(item => !item.applyType)
      if (applyTypeItem) {
        this.$message.error('请选择报销类目')
        return
      }
      const amountItem = this.formList.find(item => !item.amount)
      if (amountItem) {
        this.$message.error('报销金额不能为零或空')
        return
      }
      const costDetails = []
      for (const k of this.formList) {
        const fee = this.mattersList.find(v => v.id === k.manageCostId)
        costDetails.push({
          proFlowFeeCategoryId: k.manageCostId,
          applyType: k.applyType,
          amount: k.amount,
          apv: fee.apv,
          defaultAmt: k.defaultAmt,
          defaultBool: fee.defaulted,
          happenDate: k.happenDate,
          supply: k.supply,
          supplyRemark: k.supplyRemark,
          // fileUrl: k.fileUrl.length ? k.fileUrl.join() : ''
          fileUrl: k.fileUrl.length ? k.fileUrl : ''
        })
        if (!k.applyType) {
          this.$message.error('请选择报销类目')
          return
        }
        if (!k.amount) {
          this.$message.error('报销金额不能为零或空')
          return
        }
      }
      const personObj = this.personMap[this.personName]
      this.submitting = true
      this.addResearchPoint()
      getPmCommit({
        proFlowId: this.proFlowId,
        proId: this.projectId,
        orgId: this.centerId,
        orgDeptId: this.orgDeptId,
        userNo: this.personId,
        type: this.type,
        bankId: this.accountId,
        moneyType: this.moneyType,
        applyReason: this.applyReason,
        feeApplyDetails: JSON.stringify(costDetails),
        researchDetailId: personObj.id || '',
        researchDetailNo: personObj.researchNo || '',
        researchDetailName: personObj.name || ''
      })
        .then(res => {
          this.submitting = false
          this.$message.success('提交成功！')
          // this.$router.go(-1)
          this.$router.push({ name: 'CostApply' })
        })
        .catch(() => {
          this.submitting = false
        })
    },
    // 新增研究者费用申请埋点
    addResearchPoint () {}
  })
}
</script>
<style lang="less" scoped>
.gutter-example .ant-row > div {
  background: transparent;
  border: 0;
}
.gutter-box {
  background: #00a0e9;
  padding: 5px 0;
}
</style>
